#include "Sock.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "Usage \r\t" << proc << " port" << endl;
}

void *HandlerRequest(void *args)
{
    int sock = *(int *)args;
    delete (int *)args;

    pthread_detach(pthread_self());
#define SIZE 1024 * 10
    char buffer[SIZE];
    memset(buffer, 0, sizeof(buffer));

    ssize_t s = recv(sock, buffer, sizeof(buffer), 0);
    if (s > 0)
    {
        buffer[s] = 0;
        cout << buffer;
        string response_message = "HTTP/1.1 200 OK\r";
        response_message += "Content-Type: text/plain; charset=utf-8\n"; // text/plain,正文是普通的文本
        response_message += "\n";                         //传说中的空行
        response_message += "你看牛都在笑你！！！";

        send(sock, response_message.c_str(), response_message.size(), 0);
    }

    close(sock);
    return nullptr;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, atoi(argv[1]));
    Sock::Listen(listen_sock);
    for (;;)
    {
        int new_sock = Sock::Accept(listen_sock);

        int *pram = new int(new_sock);
        pthread_t tid;
        pthread_create(&tid, nullptr, HandlerRequest, pram);
    }

    return 0;
}